package com.ruoyi.mall.app.service.impl;


import com.ruoyi.mall.app.mapper.DtsCartMapper;
import com.ruoyi.mall.app.service.DtsOrderService;
import com.ruoyi.mall.common.domain.*;
import com.ruoyi.mall.common.mapper.DtsCommentMapper;
import com.ruoyi.mall.common.mapper.DtsCouponMapper;
import com.ruoyi.mall.common.mapper.DtsOrderMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class DtsOrderServiceImpl implements DtsOrderService {

    @Autowired
    DtsOrderMapper dtsOrderMapper;

    @Autowired
    DtsCommentMapper dtsCommentMapper;

    @Autowired
    DtsCartMapper dtsCartMapper;

    @Override
    public List<DtsOrder> selectMyOrder(DtsOrder dtsOrder) {
        return dtsOrderMapper.selectMyOrder(dtsOrder);
    }

    @Override
    public List<DtsOrder> selectOrderDetail(DtsOrder dtsOrder) {
        return dtsOrderMapper.selectMyOrderDetail(dtsOrder);
    }

    @Override
    public int quOrder(DtsOrder dtsOrder) {
        return dtsOrderMapper.updateDtsOrder(dtsOrder);
    }

    @Override
    public int delOrder(int id) {
        return dtsOrderMapper.deleteDtsOrderById(id);
    }

    @Override
    public int addComment(DtsComment comment) {
        return dtsCommentMapper.insertDtsComment(comment);
    }

    @Override
    @Transactional(rollbackFor = Exception.class) // 添加事务注解
    public Long createOrder(DtsOrder dtsOrder) {
        //订单
        dtsOrderMapper.insertDtsOrder(dtsOrder);
        //处理订单数据
        dtsOrder.getOrderGoodsList().forEach(dtsOrderGoods -> {
            dtsOrderGoods.setOrderId(dtsOrder.getId());
        });
        dtsOrderMapper.createOrderGoods(dtsOrder.getOrderGoodsList());
        return dtsOrder.getId();
    }

    @Override
    public int createOrderGoods(List<DtsOrderGoods> dtsOrderGoods) {
        return dtsOrderMapper.createOrderGoods(dtsOrderGoods);
    }

    @Override
    @Transactional(rollbackFor = Exception.class) // 添加事务注解
    public int addRefund(DtsRefundzTrace dtsRefundzTrace) {

        // 1. 先插入退款记录
        int result = dtsOrderMapper.addRefund(dtsRefundzTrace);

        if(result <= 0) {
            throw new RuntimeException("退款记录插入失败");
        }

        //更改订单状态
        DtsOrder dtsOrder = new DtsOrder();
        dtsOrder.setOrderSn(dtsRefundzTrace.getOrderSn());
        dtsOrder.setMobile(dtsRefundzTrace.getMobile());
        dtsOrderMapper.updateRefundOrder(dtsOrder);

        return result;
    }


}
